import { ActionTree } from "vuex";
import { login, userInfo as getUserInfo } from "@/api/user";
import { ElNotification, ElMessage } from "element-plus";

const state: User = {
  id: 0,
  username: "",
  name: "",
  avatar: "",
  role: [],
  permission: [],
  token: localStorage.getItem("token"),
};

const getters = {
  id: (state: User): number => state.id,
  username: (state: User): string => state.username,
  name: (state: User): string => state.name,
  avatar: (state: User): string => state.avatar,
  role: (state: User): Array<string> => state.role,
  permission: (state: User): Array<string> => state.permission,
  token: (state: User): string | null => state.token,
};

const mutations = {
  setId(state: User, id: number) {
    state.id = id;
  },
  setUsername(state: User, username: string) {
    state.username = username;
  },
  setName(state: User, name: string) {
    state.name = name;
  },
  setAvatar(state: User, avatar: string) {
    state.avatar = avatar;
  },
  setRole(state: User, role: Array<string>) {
    state.role = role;
  },
  setPermission(state: User, permission: Array<string>) {
    state.permission = permission;
  },
  setToken(state: User, token: string) {
    state.token = token;
    localStorage.setItem("token", token);
  },
};

const actions: ActionTree<User, any> = {
  setPermission({ commit }, permission: Array<string>) {
    commit("setPermission", permission);
  },
  /**
   * 登录
   * @param userInfo
   */
  async login({ commit }, userInfo) {
    const { code, data } = await login(userInfo);
    if (code === 200) {
      commit("setToken", data.token);

      const hour = new Date().getHours();
      const thisTime =
        hour < 8
          ? "早上好"
          : hour <= 11
          ? "上午好"
          : hour <= 13
          ? "中午好"
          : hour < 18
          ? "下午好"
          : "晚上好";
      ElNotification.success({
        title: `欢迎登录ikun动物园`,
        message: `${thisTime}！`,
      });
    } else {
      ElMessage({
        message: "登录失败",
        type: "error",
      });
    }
    return code;
  },
  /**
   * 获取用户信息
   * @param token
   */
  async getUserInfo({ commit }, token) {
    const { code, data } = await getUserInfo({ token });
    if (code === 200) {
      commit("setId", data.id);
      commit("setUsername", data.username);
      commit("setName", data.name);
      commit("setAvatar", data.avatar);
      commit("setRole", data.role);
      commit("setPermission", data.permission);
    }
  },
};

export default { state, getters, mutations, actions };
